package cn.lkx.eduservice.service.impl;

import cn.lkx.eduservice.client.VodClient;
import cn.lkx.eduservice.entity.EduVideo;
import cn.lkx.eduservice.mapper.EduVideoMapper;
import cn.lkx.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author lkx
 * @since 2022-05-03
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    //引入service-vod的服务
    @Autowired
    VodClient vodClient;

    //删除课程得先 根据课程id删除小节 (在课程服务层中调用)
    //TODO 后续完善删除小节视频 （多个） 先删除这些视频在删除小节
    @Override
    public boolean removeByCourseId(String courseId) {
        //1、先批量删除视频
         //根据课程id 查询出所有小节
        QueryWrapper<EduVideo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("course_id",courseId);
        queryWrapper1.select("video_source_id"); //只查这个字段就o了
        List<EduVideo> eduVideos = baseMapper.selectList(queryWrapper1);
         //收集所有视频id
        List<String> videoSourceIdList = new ArrayList<>();
        for (EduVideo eduVideo:eduVideos) {
            String videoSourceId = eduVideo.getVideoSourceId();
            if ( !StringUtils.isEmpty(videoSourceId)) {//视频id不为空
                videoSourceIdList.add(videoSourceId);
            }
        }
         //调用vod服务
        if (videoSourceIdList.size() > 0){ //判断是否为空
            vodClient.removeVideoList(videoSourceIdList);
        }
        //2、最后在删除小节记录
        QueryWrapper<EduVideo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("course_id",courseId);
        int count = baseMapper.delete(queryWrapper2);
        return count>0;
    }

    //删除小节 前先删除阿里云的视频
    @Override
    public void deleteVideoById(String videoId) { //这是小节的id
        //先获取小节对应的 视频id
        EduVideo eduVideo = baseMapper.selectById(videoId);
        String videoSourceId = eduVideo.getVideoSourceId(); //视频id
        if ( !StringUtils.isEmpty(videoSourceId) ){  //视频不为空才操作
            vodClient.deleteVideo(videoSourceId); //通过视频id删除视频
        }
    }

}
